/*
 * Copyright 2024 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.permission.api;

import com.lap.framework.i18n.entity.LocalInfo;
import com.lap.framework.i18n.helper.LangHelper;
import com.lap.framework.watchdog.annotation.Repeat;
import com.lap.permission.convert.Convert;
import com.lap.permission.domain.entity.DictDetail;
import com.lap.permission.dto.request.DictDetailRequest;
import com.lap.permission.service.DictDetailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <pre>
 *  数字字典明细 Controller,控制业务流程。
 *  提供包括业务流程校验,业务流程控制。当流程非常复杂时候,请在API和Service之间添加一层Manager。
 *  Controller 对外开放Rest,同时可以做简单流程控制。Manager复杂流程控制。Service数据完整性(事务)。DAO/Mapper持久操作。
 *  流程简单: Controller->Service->DAO
 *  复杂流程: Controller->Manager->Service->DAO
 *  对外流程: Controller->Manager->Service->DAO
 * 					    |->外部服务
 *  <b>uri 规则</b>
 *   uri 名词复数.
 *   列表或分页 : GET /persons
 *   单人信息   : GET /persons/1
 *   新增      : POST /persons
 *   修改      : PUT /persons
 *   删除      : DELETE /persons/1
 * </pre>
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 * @see DictDetailService
 * @see DictDetailRequest
 * @see DictDetail
 */
@Tag(name = "数字字典明细")
@RequiredArgsConstructor
@RestController
@RequestMapping("api/dict-details")
public class DictDetailController {

    private final DictDetailService dictDetailService;

    private final Convert convert;

    @Operation(summary = "根据编码数字字典明细")
    @PostMapping("list")
    public Map<String, List<DictDetail>> queryByDictCodes(@RequestBody List<String> dictCodes) {
        LocalInfo localInfo = LangHelper.get();
        return dictDetailService.queryByDictCodes(dictCodes, localInfo.storeLang());
    }

    @Operation(summary = "根据ID查询数字字典明细")
    @GetMapping("{dictId}")
    public List<DictDetail> queryByDictId(@PathVariable Integer dictId) {
        return dictDetailService.queryByDictId(dictId);
    }

    @Operation(summary = "数字字典明细新增")
    @Repeat
    @PostMapping
    public Integer saveDictDetail(@RequestBody @Validated DictDetailRequest request) {
        List<DictDetail> list = request.getDataList().stream()
                .map(item -> toDto(request, item))
                .toList();
        return dictDetailService.insertDictDetail(request.getDictId(), list);
    }

    private DictDetail toDto(DictDetailRequest request, DictDetailRequest.DetailRequest detail) {
        DictDetail dictDetail = convert.toDictDetail(detail);
        dictDetail.setDictId(request.getDictId());
        dictDetail.setDictCode(request.getDictCode());
        return dictDetail;
    }

}
